<template>
  <div class="projectsview">
    <header class="header">
      <img class="logo" src="@/UI/assets/logoCAEStudio.svg" alt="logo" />
      <div class="user">
        <img alt="avatar" src="@/UI/assets/avatar.svg" class="avatar" />
        <span class="username">用户名</span>
      </div>
    </header>
    <ProjectEmpty
      v-if="cardsData.length === 0 && firstLoad"
      @refresh="refresh"
    />
    <div class="content" v-else>
      <div class="title">
        <h1>项目列表</h1>
        <Input
          placeholder="搜索..."
          style="max-width: 320px"
          :value="searchValue"
          @change="handleChange"
          @click="handleSearch"
          :clearable="true"
        >
          <template #suffix>
            <img src="@/UI/assets/search.svg" />
          </template>
        </Input>
      </div>
      <div class="cards" ref="elementToWatch" v-if="cardsData.length > 0">
        <CreateCard @refresh="refresh" />
        <template v-for="(item, index) in cardsData" :key="index">
          <ProjectCard @refresh="refresh" :card="item" />
        </template>
      </div>
      <SearchEmpty v-else />
      <div class="loading">
        <Spin :active="loading" tip="Loading..." />
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { Input, Spin } from "cax-ui";
import ProjectEmpty from "@/UI/components/projects/ProjectEmptyComp.vue";
import SearchEmpty from "@/UI/components/projects/SearchEmptyComp.vue";
import ProjectCard from "@/UI/components/projects/projectCard.vue";
import CreateCard from "@/UI/components/projects/createCard.vue";
import { onMounted, onUnmounted, ref, watch, defineComponent } from "vue";
import { getAllProjects } from "@/UI/api/projects";
interface Project {
  name: string;
  id: string;
  image?: string;
}
const cardsData = ref<Project[]>([]);
const searchValue = ref("");
const currentPage = ref(1);
const pageSize = ref(20);
const total = ref(0);
const firstLoad = ref(true);
const loading = ref(false);
const elementToWatch = ref<HTMLElement | null>(null);
const debounceTimeout = ref<any>(0);

// 异步函数，用于获取项目列表
async function getProjects() {
  // 定义请求参数
  const params = {
    page: currentPage.value, // 当前页码
    size: pageSize.value, // 每页显示数量
    search: searchValue.value, // 搜索关键字
    // TODO 暂时写死
    userId: "97a9d9b1-89c1-4bcf-a2ed-94c4c46fa904", // 用户ID
  };
  // 发送请求
  await getAllProjects(params)
    .then((res) => {
      // 解析响应数据
      const { current, size, total: t, data } = res;
      // 更新当前页码、每页显示数量、总数量
      currentPage.value = current;
      pageSize.value = size;
      total.value = t;
      // 如果当前页码不为1，则将数据追加到cardsData中
      if (currentPage.value !== 1) {
        cardsData.value = cardsData.value.concat(data);
      } else {
        // 如果是第一次加载且数据不为空，则将firstLoad置为false
        if (firstLoad.value && data.length > 0) {
          firstLoad.value = false;
        }
        // 否则，将数据赋值给cardsData
        cardsData.value = data;
      }
    })
    .catch((err) => {
      // 打印错误信息
      console.log(err, "err");
    })
    .finally(() => {
      // 关闭加载状态
      loading.value = false;
    });
}
function refresh() {
  console.log("refresh");
  currentPage.value = 1;
  firstLoad.value = true;
  getProjects();
}
function handleChange(e: string) {
  console.log("handleChange", e);
  searchValue.value = e;
  currentPage.value = 1;
  getProjects().then();
}
function handleSearch() {
  currentPage.value = 1;
  getProjects().then();
}

function handleScroll() {
  clearTimeout(debounceTimeout.value);
  if (!elementToWatch.value) return;
  debounceTimeout.value = setTimeout(() => {
    const rect: any = elementToWatch.value?.getBoundingClientRect();
    const distanceToBottom = rect.height + rect.top - window.innerHeight;
    // 设置一个阈值，当距离小于该值时发起请求
    const threshold = 300; // 根据需求调整
    if (distanceToBottom >= threshold) return;
    if (total.value > 0 && cardsData.value.length >= total.value) return;
    // 满足条件时执行接口请求
    currentPage.value += 1;
    loading.value = true;
    getProjects();
  }, 30);
}
onMounted(() => {
  getProjects().then();
  handleScroll();
  window.addEventListener("scroll", handleScroll);
  window.addEventListener("resize", handleScroll);
});
onUnmounted(() => {
  window.removeEventListener("scroll", handleScroll);
});
</script>
<style lang="less" scoped>
.projectsview {
  position: relative;
  z-index: 1;

  .header {
    height: 48px;
    padding: 0 24px;
    position: fixed;
    width: 100%;
    box-sizing: border-box;
    background-color: #ffffff;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #e9ecff;
    // position: relative;
    z-index: 2;

    .logo {
      width: 152px;
      height: 20px;
    }

    .user {
      display: flex;
      align-items: center;

      .avatar {
        width: 32px;
        height: 32px;
        border-radius: 50%;
      }

      .username {
        margin-left: 8px;
        font-size: 14px;
        font-family: PingFang SC;
        line-height: 22px;
        color: #495057;
      }
    }
  }

  .content {
    min-height: calc(100vh - 96px);
    background-color: #f1f2f4;
    padding: 24px;
    padding-top: 72px;

    .title {
      display: flex;
      justify-content: space-between;
      align-items: center;

      h1 {
        font-family: PingFang SC;
        font-size: 18px;
        font-weight: 600;
        line-height: 26px;
        letter-spacing: 0em;
        color: #212529;
        padding: 3px 0;
        margin: 0;
      }

      img {
        cursor: pointer;
      }
    }

    .cards {
      margin-top: 16px;
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(361.5px, 1fr));
      gap: 16px;
    }

    .loading {
      margin-top: 25px;
      width: 100%;
    }
  }
}

:deep(.vxp-input) {
  background-color: transparent !important;
}
</style>
